// src/stores/rolesStore.js
import {defineStore} from 'pinia'
import * as roleApi from "@/api/roles";

export const useRolesStore = defineStore('roles', {
    state: () => ({
        rolesList: [],
        loading: false,
        isFetching: false // 新增状态标志
    }),
    getters: {
        getRoles(state) {
            return state.rolesList
        },
    },
    actions: {
        async fetchRoles(force = false) {
            // 如果已经在获取中且未强制刷新，则直接返回
            if (this.isFetching && !force) {
                return Promise.resolve(this.rolesList)
            }

            this.loading = true
            this.isFetching = true
            
            try {
                // 检查是否已有数据且非强制刷新
                if (this.rolesList && this.rolesList.length > 0 && !force) {
                    return this.rolesList
                }

                this.rolesList = await fetchRolesList()
                return this.rolesList
            } catch (error) {
                console.error('获取角色失败:', error)
                return this.rolesList
            } finally {
                this.loading = false
                this.isFetching = false
            }
        },

        toggleCollapse() {
            this.collapse = !this.collapse
        }
    },

})


// 从 store 获取角色列表（不再直接调用 API）
async function fetchRolesList() {
    return roleApi.getRoles().then(data => data.data);
}
